//
//  CJMgmtForm.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/4/8.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit
 
class CJMgmtForm: GlobalFormVC,operatable,refreshable,DateWidgetableOK,BatchSelectable,KSImageUtilDelegate {
    var item1 :KSFormHItem = {
        let appe = KSFormHAppear()
            .roundType(.top)
        let v = KSFormHItem(title: "成交编号",appearance:appe)
        v.disabled = true

        return v
    }()
    var item2 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "竞拍编号*",appearance:appe )
         return v
    }()
    var item3 :KSFormHItem = {
        let appe = KSFormHAppear()
         let v = KSFormHItem(title: "成交标题*",appearance:appe )
 
         return v
    }()
    var item4 :KSFormHItem = {
        let appe = KSFormHAppear()
         let v = KSFormHItem(title: "单据行业类型",appearance:appe )
        v.disabled = true
        return v
    }()
    var item5 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "猪只品种",appearance:appe )
        v.disabled = true
        return v
    }()
    var item6 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "商品名称",appearance:appe )
        v.disabled = true
        return v
    }()
    var item7 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "数量(头)",appearance:appe )
        v.disabled = true
        return v
    }()
    var item8 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "起拍数量(头)",appearance:appe )
        v.disabled = true
        return v
    }()
    var item9 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "均重(KG)",appearance:appe )
        v.disabled = true
        return v
    }()
    var item10 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "计量单位",appearance:appe )
        v.disabled = true
        return v
    }()
    var item11 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "起拍价(元)",appearance:appe )
        v.disabled = true
        return v
    }()
    var item12 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "账期",appearance:appe )
        v.disabled = true
        return v
    }()
    var item13 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "竞价幅度(元)",appearance:appe )
        v.disabled = true
        return v
    }()
    var item14 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "开始时间*",appearance:appe )
        v.disabled = true
        return v
    }()
    var item15 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "结束时间*",appearance:appe )
        v.disabled = true
        return v
    }()
    var item16 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "出栏时间(开始)*",appearance:appe )
        v.disabled = true
        return v
    }()
    var item17 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "出栏时间(结束)*",appearance:appe )
        v.disabled = true
        return v
    }()
    var item18 :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentHight(45)
        let v = KSFormHItem(title: "发布单位",appearance:appe,type:.tempTextView )
        v.disabled = true
        return v
    }()
    var item19 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "发布猪场",appearance:appe )
        v.disabled = true
        return v
    }()
    var item20 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "省*",appearance:appe )
        v.disabled = true
        return v
    }()
    var item21 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "城市*",appearance:appe )
        v.disabled = true
        return v
    }()
    var item22 :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentHight(80)
        let v = KSFormHItem(title: "地址*",appearance:appe,type:.tempTextView )
        v.disabled = true
        return v
    }()
    var item23 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "联系人*",appearance:appe )
        v.disabled = true
        return v
    }()
    var item24 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "联系方式*",appearance:appe )
        v.disabled = true
        return v
    }()
    var item25 :KSFormHItem = {
        let appe = KSFormHAppear()
            .segTitleArr(["启用","禁用"])
        let v = KSFormHItem(title: "启用状态",appearance:appe,type: .segment )
        return v
    }()
    var item26 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "制单人",appearance:appe )
        v.disabled = true
        return v
    }()
    var item27 :KSFormVItem = {
        let appe = KSFormVAppear()
         let v = KSFormVItem(title: "备注",appearance:appe)
        return v
    }()
    var item28 :KSFormHItem = {
        let appe = KSFormHAppear()
         let v = KSFormHItem(title: "操作时间",appearance:appe )
        v.disabled = true
        return v
    }()
    var item29 :KSFormVItem = {
        let appe = KSFormVAppear()
            .contentHight(80)
        let v = KSFormVItem(title: "成交说明",appearance:appe,type:.tempTextView )
        return v
    }()
    var main = CJMgmtModel(JSON:["":""])!
    var details = [CJClientInfo]()
    
    static func initForFix(model:CJMgmtModel) -> CJMgmtForm {
        
        let vc = CJMgmtForm()
        vc.excuteType = .fix
        vc.main = model
        return vc
    }
    static func initForView(model:CJMgmtModel) -> CJMgmtForm {
        
        let vc = CJMgmtForm()
        vc.excuteType = .view
        vc.main = model
        return vc
    }
    static func initForAudit(model:CJMgmtModel) -> CJMgmtForm {
        
        let vc = CJMgmtForm()
        vc.excuteType = .audit
        vc.main = model
        return vc
    }
    static func initForAdd() -> CJMgmtForm {
        
        let vc = CJMgmtForm()
        vc.excuteType = .add
           vc.main.zOrgId = USERINFO.zOrgId
           vc.main.zOrgNm = USERINFO.zOrgNm
        vc.main.zDeptId = USERINFO.deptId
      vc.main.zDeptNm = USERINFO.deptNm
 
        vc.main.zDate = Date.today
        vc.main.zStaffId = USERINFO.idKey.unwrap
        vc.main.zStaffNm = USERINFO.zName.unwrap
          vc.main.zUse = "1"
        //        vc.main.zNewlyNm = USERINFO.zName.unwrap
        return vc
    }
    
    var attr = [VideoImg]()
    
    // 防止外面乱初始化，并提供静态方法给调用者
    private init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "成交管理"
        
        
        
        if self.excuteType == .add || excuteType == .fix {
            let saveBtn = UIBarButtonItem(title: "保存", style: .done, target: self, action: #selector(saveAction))
            
            saveBtn.tintColor = .black
            
            
            self.navigationItem.rightBarButtonItem = saveBtn
        }
        
        self.tableVw.register(GlobalSectionHeader.self, forHeaderFooterViewReuseIdentifier: GlobalSectionHeader.identifier)
        tableVw.register(GlobalAddTableCell.self, forCellReuseIdentifier: GlobalAddTableCell.identifier)
        
        self.tableVw.register(CJMgmtFormCell.self, forCellReuseIdentifier: CJMgmtFormCell.identifier)
        
        if excuteType == .fix || excuteType == .view || excuteType == .audit {
            
            KSNetwork.shared.doRequest(API.homepage(.CJMg_getAuctionInfoForm(id_key: self.main.idKey.unwrap))) { (data:BaseResultOK<CJMgmtModel>) in
                if data.flag == TRUE {
                    if let info = data.infoObjCombine {
                        self.main = info
                        if let dets = info.clientInfo {
                            self.details = dets
                        }
                        if let picA = info.picInfo {
                            self.attr.removeAll()
 
                            for item in picA {
                                var ttt:SourType = .file
                                if item.zPicUrl.unwrap.contains("png") || item.zPicUrl.unwrap.contains("jpg") ||
                                    item.zPicUrl.unwrap.contains("jpeg") {
                                    ttt = .image
                                }
                                var one = VideoImg(type: ttt, idkey: item.idKey.unwrap, url: configURLOK(latter: item.zPicUrl.unwrap), name: item.zName.unwrap)
                                if ttt == .image {
                                    one.image = getPicture(url: one.url.unwrap)
                                }
                                self.attr.append(one)
                            }
 
                            self.configView()
                            self.configAction()
                            self.configDataSource()
                            self.tableVw.reloadData()
                        }
 
                    }
                    
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        } else {
            configView()
            configAction()
            configDataSource()
        }
        
        
    }
    
    func configView() {
        
        bg.add(item1).add(item2).add(item3).add(item4).add(item5).add(item6).add(item7).add(item8).add(item9).add(item10).add(item11).add(item12).add(item13).add(item14).add(item15).add(item16).add(item17).add(item18).add(item19).add(item20).add(item21).add(item22).add(item23).add(item24).add(item25).add(item26).add(item27).add(item28).add(item29)
        
        
        let viewFlag:ImgViewType = (excuteType == .view) ? .viewOnly : .editable
        imageUtil = KSImageSelectUtil(frame: CGRect(x:0,y:item29.frame.maxY,width:bg.ks_width ,height:imgHeight/2),httpHeader: USERINFO.picUrl.unwrap,numberOfRow: 5,viewType:viewFlag)
        imageUtil?.ksDelegate = self
        bg.addv(view:imageUtil!)
        self.imageUtil!.newestShow(arr: self.attr)
        
        header.ks_height = bg.frame.maxY
        self.tableVw.tableHeaderView = header
    }
    func configAction() {
 
        
        item2.actionClosure = {
            let vc = KSSingleSelectNetUtil()
            vc.title = "选择"
            vc.kSSingleSelectNetNetwork = { page,size,keyword in
                KSNetwork.shared.doRequest(API.homepage(.CJMg_getJpNmList(z_record_no: keyword, page: "\(page)", size: "\(size)"))) { (data:BaseResultOK<CJjplistM>) in
                    if data.flag == TRUE {
                        if let infos = data.infos {
                            if page == 1 {
                                vc.allArr.removeAll()
                            }
                            vc.showData(arr:infos)
                        }
                    } else {
                        KSToast("错误")
                    }
                }
            }
            vc.kSSingleSelectNetShowCell = { cell,model in
                var contArr:[(String,String?)]!
                 
                
              contArr = [
                           ("竞拍编号","\((model as! CJjplistM).zRecordNo.unwrap)")
                          ,("竞拍标题","\((model as! CJjplistM).zTitle.unwrap)")
                           ,("猪场名称","\((model as! CJjplistM).zZcNm.unwrap)")

                         ,("商品名称","\((model as! CJjplistM).zGoodsNm.unwrap)")
                           ,("猪只品种","\((model as! CJjplistM).zPigType.unwrap)")
                             ,("创建时间","\((model as! CJjplistM).zCreateTm.unwrap)")
                   ]
              cell.setDataSource(contentArr: contArr)
              
             }
 
            vc.backClosure = { model in
                
                self.main.zZbNo = (model as! CJjplistM).zRecordNo.unwrap
                self.main.zZbId = (model as! CJjplistM).idKey.unwrap

                self.main.zPigType = (model as! CJjplistM).zPigType.unwrap
                self.main.zGoodsNm = (model as! CJjplistM).zGoodsNm.unwrap
                self.main.zNum = (model as! CJjplistM).zNum.unwrap
                self.main.zLeastNum = (model as! CJjplistM).zLeastNum.unwrap
                 self.main.zAvgWeight = (model as! CJjplistM).zAvgWeight.unwrap
                self.main.zUnitNm = (model as! CJjplistM).zUnitNm.unwrap
                self.main.zPrice = (model as! CJjplistM).zPrice.unwrap
                self.main.zZq = (model as! CJjplistM).zZq.unwrap
                self.main.zRange = (model as! CJjplistM).zRange.unwrap
                self.main.zBeginDate = (model as! CJjplistM).zBeginDate.unwrap
                self.main.zEndDate = (model as! CJjplistM).zEndDate.unwrap
                self.main.zDate = (model as! CJjplistM).zDate.unwrap
                self.main.zDateEnd = (model as! CJjplistM).zDateEnd.unwrap
                self.main.zOrgId = (model as! CJjplistM).zOrgId.unwrap
                self.main.zOrgNm = (model as! CJjplistM).zOrgNm.unwrap
                self.main.zDeptId = (model as! CJjplistM).zDeptId.unwrap
                self.main.zDeptNm = (model as! CJjplistM).zDeptNm.unwrap

                self.main.zProvince = (model as! CJjplistM).zProvince.unwrap
                self.main.zCity = (model as! CJjplistM).zCity.unwrap
                self.main.zAddress = (model as! CJjplistM).zAddress.unwrap
                self.main.zName = (model as! CJjplistM).zName.unwrap
                self.main.zTel = (model as! CJjplistM).zTel.unwrap
                self.main.zZcNm = (model as! CJjplistM).zZcNm.unwrap
                self.main.zZcId = (model as! CJjplistM).zZcId.unwrap

                self.configDataSource()
 
            }
            self.navigationController?.pushViewController(vc,animated:true)
            
            
        }
        item3.textValueChangeClo = {str in
            self.main.zTitle = str

        }
 
        item5.actionClosure = {
            
            let vc = KSSingleSelectNetUtil()
            vc.title = "选择"
            vc.kSSingleSelectNetNetwork = { page,size,keyword in
                KSNetwork.shared.doRequest(API.homepage(.JPMg_getGoodsNm(name: keyword, page: "\(page)", size: "\(size)"))) { (data:BaseResultOK<JPMGoodsM>) in
                    if data.flag == TRUE {
                        if let infos = data.infos {
                            if page == 1 {
                                vc.allArr.removeAll()
                            }
                            vc.showData(arr:infos)
                        }
                    } else {
                        KSToast("错误")
                    }
                }
            }
            vc.kSSingleSelectNetShowCell = { cell,model in
                
                
                var contArr:[(String,String?)]!
                 
                
              contArr = [
                           ("产品名称:","\((model as! JPMGoodsM).zProductNm.unwrap)")
                           ,("描述:","\((model as! JPMGoodsM).productDescribe.unwrap)")
                           ,("计价方式:","\((model as! JPMGoodsM).zUnitNm.unwrap)")
                           ,("产品合同名称:","\((model as! JPMGoodsM).productContractNm.unwrap)")


                       ]
              cell.setDataSource(contentArr: contArr)
                
                  
            }
            vc.backClosure = { model in
                
                self.main.zGoodsNm = (model as! JPMGoodsM).zProductNm.unwrap
                
                self.configDataSource()
                
                
            }
            self.navigationController?.pushViewController(vc,animated:true)
            
            
            
        }
  
        item25.segmentChangeClo = { tagx,titlex  in
            self.main.zUse = titlex == "启用" ? "1" : "0"
        }
      
        item27.textValueChangeClo = { str in
            self.main.zRemark = str
        }
        item29.textValueChangeClo = { str in
            self.main.zContent = str
        }
    }
    
    
    func configDataSource() {
        main.zDtradeType = "1"
        item1.setVal(self.main.zRecordNo)
        item2.setVal(self.main.zZbNo)
        item3.setVal(self.main.zTitle)
        item4.setVal(TradeDic[self.main.zDtradeType.unwrap])
        item5.setVal(self.main.zPigType)
         item6.setVal(self.main.zGoodsNm)
        item7.setVal(self.main.zNum)
        item8.setVal(self.main.zLeastNum)
        item9.setVal(self.main.zAvgWeight)
        item10.setVal(self.main.zUnitNm)
        item11.setVal(self.main.zPrice)
        item12.setVal(self.main.zZq)
         item13.setVal(self.main.zRange)
         item14.setVal(self.main.zBeginDate)
        item15.setVal(self.main.zEndDate)
        item16.setVal(self.main.zDate)
        item17.setVal(self.main.zDateEnd)
        item18.setVal(self.main.zOrgNm)
        item19.setVal(self.main.zZcNm)
        item20.setVal(self.main.zProvince)
        item21.setVal(self.main.zCity)
        item22.setVal(self.main.zAddress)
        item23.setVal(self.main.zName)
        item24.setVal(self.main.zTel)
        var v25 = ""
        if self.main.zUse == "0" {
            v25 = "禁用"
        } else if self.main.zUse == "1"  {
            v25 = "启用"
        }
        item25.setSegmentSelectTitle(v25)
        item26.setVal(self.main.zStaffNm)
        item27.setVal(self.main.zRemark)
        item28.setVal(self.main.zCreateTm)
        item29.setVal(self.main.zContent)
 
    }
    
    
    func dealBeforeAddImages(_ util: KSImageSelectUtil, imgs: [UIImage]) -> [UIImage] {
        return  commonPigWaterMark(imgs: imgs)
    }
    func addImages(_ util: KSImageSelectUtil, imgvideos: [VideoImg]) {
        self.attr += imgvideos
    }
    func deleteImage(_ util: KSImageSelectUtil, index: Int) {
        let one = self.attr[index]
        if one.idkey.unwrap.isEmpty {
            self.attr.remove(at: index)
            self.imageUtil!.deleteLocalImg(tag: index)
        } else {
            alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                 KSNetwork.shared.doRequest(API.homepage(.JPMg_delPic(id_key: one.idkey.unwrap))) { (data:BaseResult<OperateResult>) in
                    if data.flag == TRUE {
                        KSToast("删除成功")
                        self.attr.remove(at: index)
                        self.imageUtil!.deleteLocalImg(tag: index)
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                 }

            })])
           
        }
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section != self.details.count {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: CJMgmtFormCell.identifier, for: indexPath) as? CJMgmtFormCell else {
                fatalError()
            }
            
            cell.one = self.details[indexPath.section]
            
            cell.item1.actionClosure = { [indexPath] in
                guard self.main.zZbId.unwrap != "" else {
                    KSToast("先选竞拍编号")
                    return
                }
                let vc = KSSingleSelectNetUtil()
                vc.title = "选择"
                vc.kSSingleSelectNetNetwork = { page,size,keyword in
                    KSNetwork.shared.doRequest(API.homepage(.CJMg_getAuctionNmList(z_record_no: keyword, z_zb_id: self.main.zZbId.unwrap , page: "\(page)", size: "\(size)"))) { (data:BaseResultOK<CJClientInfo>) in
                        if data.flag == TRUE {
                            if let infos = data.infos {
                                if page == 1 {
                                    vc.allArr.removeAll()
                                }
                                vc.showData(arr:infos)
                            }
                        } else {
                            KSToast("错误")
                        }
                    }
                }
                vc.kSSingleSelectNetShowCell = { cell,model in
                    var contArr:[(String,String?)]!
                      
                    
                  contArr = [
                        ("出价编号","\((model as! CJClientInfo).zRecordNo.unwrap)")
                        ,("出价单位","\((model as! CJClientInfo).zTbCompany.unwrap)")
                        ,(" 出价(元)","\((model as! CJClientInfo).zPrice.unwrap)")
                        ,("竞拍数量","\((model as! CJClientInfo).zBidNum.unwrap)")
                        ,("省","\((model as! CJClientInfo).zProvince.unwrap)")
                        ,("市","\((model as! CJClientInfo).zCity.unwrap)")
                        ,("地址","\((model as! CJClientInfo).zAddress.unwrap)")
                        ,("联系人","\((model as! CJClientInfo).zName.unwrap)")
                        ,("联系方式","\((model as! CJClientInfo).zTel.unwrap)")
                        ,("创建时间","\((model as! CJClientInfo).zCreateTm.unwrap)")
                        ,("出价说明","\((model as! CJClientInfo).zContent.unwrap)")

                       ]
                  cell.setDataSource(contentArr: contArr)
                  
                 }
 
                vc.backClosure = {[indexPath] model in
                    
                    let fArr = self.details.filter { $0.idKey.unwrap == (model as! CJClientInfo).idKey.unwrap }
                    guard fArr.count < 1 else {
                        KSToast("已存在相同的出价单位")
                        return
                    }
 
                    self.details[indexPath.section].idKey = (model as! CJClientInfo).idKey.unwrap
                     self.details[indexPath.section].zRecordNo = (model as! CJClientInfo).zRecordNo.unwrap
                    self.details[indexPath.section].zPrice = (model as! CJClientInfo).zPrice.unwrap
                    self.details[indexPath.section].zJpPrice = (model as! CJClientInfo).zPrice.unwrap
                    self.details[indexPath.section].zBidNum = (model as! CJClientInfo).zBidNum.unwrap
                 self.details[indexPath.section].zZbNum = (model as! CJClientInfo).zZbNum.unwrap
                     self.details[indexPath.section].zName = (model as! CJClientInfo).zName.unwrap
                    self.details[indexPath.section].zTel = (model as! CJClientInfo).zTel.unwrap
                    self.details[indexPath.section].zTbCompany = (model as! CJClientInfo).zTbCompany.unwrap
                    self.details[indexPath.section].zCreateTm = (model as! CJClientInfo).zCreateTm.unwrap
                    self.details[indexPath.section].zContent = (model as! CJClientInfo).zContent.unwrap

            
                    self.tableVw.reloadData()
                    
                    
                }
                self.navigationController?.pushViewController(vc,animated:true)
                
 
            }
            cell.item2.textValueChangeClo = {[indexPath] str in
                self.details[indexPath.section].zPrice = str
            }
            cell.item4.textValueChangeClo = {[indexPath] str in
                self.details[indexPath.section].zZbNum = str
            }
            return cell
        }  else  {  // +
            let cell = tableView.dequeueReusableCell(withIdentifier: GlobalAddTableCell.identifier, for: indexPath) as! GlobalAddTableCell
            cell.titleLab.text = "+  添加"
            return cell
        }
        
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.details.count + 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == self.details.count {
            return 1
        } else {
            if self.details[section].openx == true {
                return 1
            } else {
                return 0
            }
        }
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == self.details.count {
            
            let one = CJClientInfo(JSON: ["" : ""])!
            self.details.append(one)
            self.configDataSource()
            self.tableVw.reloadData()
            
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == self.details.count  {
            return sectionHeaderHeight
        }   else {
            return 360
            
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == self.details.count {
            return 0
        } else {
            return sectionHeaderHeight
        }
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        
        guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: GlobalSectionHeader.identifier) as? GlobalSectionHeader else {
            fatalError()
        }
        let tap = UITapGestureRecognizer()
        tap.numberOfTapsRequired = 1
        tap.addTap { [unowned self] _ in
            self.details[section].openx = !self.details[section].openx
            let set = IndexSet(integer:section)
            tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
            
        }
        
        headerView.addGestureRecognizer(tap)
        
        
        if self.excuteType == .add  || self.excuteType == .fix {
            headerView.deleteClo = {
                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                    self.details.remove(at: section)
                    self.countSum()
                    self.configDataSource()
                    self.tableVw.reloadData()
                })])
                
            }
            headerView.delBtn.isHidden = false
        } else {
            headerView.delBtn.isHidden = true
        }
        
        
        headerView.setOpenx(flag: self.details[section].openx)
     
        
        
        headerView.setTitle("成交明细\(section + 1)")
        return headerView
        
        
    }
    func countSum() {
        //        let sum = self.details.compactMap { doubleTran($0.zPlanNum) }.reduce(0, +)
        //        self.main.zNum = "\(sum.roundTo(0))"
    }
    
    // MARK: - 提交
    @objc func saveAction() {
        
        guard self.judgeNoNone() else {
            return
        }
        
        let vali = Validation()
        vali.expression(self.details.count > 0, msg: "至少需要一条成交明细")

        for i in 0..<self.details.count {
               vali.required(value: self.details[i].zZbNum, msg: "第\(i + 1)条细表，成交数量不能为空!")
         }
        
        // 需求改为  允许超过
//        let sumN = self.details.compactMap{doubleTran($0.zZbNum)}.reduce(0, +)
//        vali.expression(doubleTran(self.main.zNum) >= sumN, msg: "成交明细数量不能超过总数量")
        guard vali.validate() else {
            return
        }
        
        
        let masterjson = dictionaryToJson(self.main.dictionaryRepresentation())
        
        
        let detailsss = self.details.compactMap { dictionaryToJson($0.dictionaryRepresentation()) }.joined(separator: ",")
        let dataJson = "[" + detailsss + "]"
        
        // 有附件就传
        
        let unUploadF = self.attr.filter{ $0.idkey.unwrap == "" }
     
        
        var api:API?
        if excuteType == .fix {
            api = API.homepage(.CJMg_updateAuctionInfo(data: masterjson, detail: dataJson, files: unUploadF))
        } else {
            api = API.homepage(.CJMg_saveAuctionInfo(data: masterjson, detail: dataJson, files: unUploadF))
        }
        
         KSNetwork.shared.doRequest(api!) {[weak self] (data:BaseResultOK<OperateResult>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                KSToast("保存单据成功")
                self.backAction()
                
                
            } else {
                
                KSToast(data.errorCombine.unwrap)
                
            }
        }
        
        
    }
 
    func backAction() {
        if let clo = self.refreshClosure {
            clo()
        }
        self.navigationController?.popViewController(animated: true)
    }
    
    
    
}
